(function(window, document, $) {

	function createPanel(panel) {
		panel = $.extend({}, $.fn.timeline.defaults.style, panel); //fulfill with default value if not pass in.

		var $avatar = $('<img />').addClass('user-photo').attr('src', panel.user.avatar);
		var $username = $('<strong />').addClass('user-name').append(panel.user.name);
		var $datetime = $('<small />').addClass('text-muted').append(panel.date);
		var $panelHead = $('<div />').addClass('panel-heading').append($avatar).append($username).append($datetime);
		
		var $panelBody = $('<div />').addClass('panel-body').append(panel.content).append(panel.child ? createPanel(panel.child) : "");

		var $panel = $('<div />').addClass('panel').addClass('panel-' + panel.panelType).append($panelHead, $panelBody);
		
		return $panel;
	}

	var Timeline = function(element, options) {
		this.$element = $(element);
		this.options = $.extend({}, $.fn.timeline.defaults, this.$element.data(), options);
	
		this.get = function(option) {
			return options[option];
		}
		this.set = function(option, value) {
			options[option] = value;
		}
		this.init();
	}

	Timeline.prototype = {
		constructor: Timeline,
		
		init: function() {
			this.create();
		},
		destroy: function() {
			
		},
		create: function() {
			var self = this;
			var timeline = $("<ul />").addClass('timeline').addClass(self.options.singleSide ? 'timeline-single-side' : '');
			self.$timeline = timeline.appendTo($element);
			// this.render(demoData);
		},
		render: function(data) {
			var self = this;
			for (i = 0; i < data.length; i++) {
				this.addNode(data[i]);
			}
		},
		addNode: function(node) {
			var self = this;
			self.$timeline.append(self.options.buildNode.call(this, node));
		}
	}

	$.fn.timeline = function(options) {
		return this.each(function() {
			$element = this;
			// var timeline = Object.create(Timeline);
			var timeline = new Timeline();
			$.data($element, "timeline", timeline);
		})
	};

	$.fn.timeline.defaults = {
		// PROPERTIES
		mode: 'horizontal', // vertical
		singleSide: true,
		style: {
			badgeType: 'info',
			badgeIcon: 'heart',
			panelType: 'info'
		},

		// CONTROLS
		iconClass: function(icon) {
			return "glyphicon glyphicon-" + icon;
		},
		buildNode: function(node) {
			var self = this;
			$badgeIcon = $('<i/>').addClass(self.options.iconClass.call(this, node.badgeIcon));
			$badge = $('<div />').addClass('timeline-badge').addClass(node.badgeType).append($badgeIcon);

			$content = createPanel(node);
			$card = $('<div />').addClass('timeline-card').addClass('timeline-unbordered').append($content);

			$node = $('<li/>').append($badge).append($card);

			return $node;
		}
	};

})(window, document, $);